package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

import grails.converters.JSON

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class NoteController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def noteList = Note.findAll("from Note where user.username = '${username}' order by modifiedDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Note.executeQuery("select count(id) from Note where user.username = '${username}'")

        respond noteList, model: [noteCount: count[0], params: params]
    }

    def show(Note note)
    {
        respond note
    }

    def create()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)
        def targetUri = request.getHeader("referer")
        respond new Note(params), model: [targetUri: targetUri, user: user]
    }

    @Transactional
    def save(Note note)
    {
        if (note == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (note.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond note.errors, view: 'create'
            return
        }

        note.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'note.label', default: 'Note'), note.id])
                redirect uri: params['targetUri']
            }
            '*' { respond note, [status: CREATED] }
        }
    }

    @Transactional
    def tempSave(Note note)
    {
        if (note.validate())
        {
            note.save flush: true
        }
        else
        {
            log.info "tempSave note error: " + note.errors
        }

        render([status: "success", id: note?.id, userId: note?.user?.id] as JSON)
    }

    def edit(Note note)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)
        def targetUri = request.getHeader("referer")
        def permission = false

        TeamRole editTeamRole = TeamRole.findByName('Edit')

        if (note.user.id == user.id)
        {
            permission = true
        }
        else if (params['teamName'])
        {
            def notePermission
            switch (params['teamName'])
            {
            case "contactTeam":
                notePermission = ContactTeam.findByContactAndUser(note?.contact, user)?.notePermission
                if (notePermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "accountTeam":
                notePermission = AccountTeam.findByAccountAndUser(note?.account, user)?.notePermission
                if (notePermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "opportunityTeam":
                notePermission = OpportunityTeam.findByOpportunityAndUser(note?.opportunity, user)?.notePermission
                if (notePermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "campaignTeam":
                notePermission = CampaignTeam.findByCampaignAndUser(note?.campaign, user)?.notePermission
                if (notePermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "assetTeam":
                notePermission = AssetTeam.findByAssetAndUser(note?.asset, user)?.notePermission
                if (notePermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            }
        }

        if (permission)
        {
            respond note, model: [targetUri: targetUri, user: user]
        }
        else
        {
            flash.message = "没有编辑权限"
            redirect uri: request.getHeader("referer")
        }
    }

    @Transactional
    def update(Note note)
    {
        if (note == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (note.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond note.errors, view: 'edit'
            return
        }
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        note.modifyBy = user

        note.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'note.label', default: 'Note'), note.id])
                redirect uri: params['targetUri']
            }
            '*' { respond note, [status: OK] }
        }
    }

    @Transactional
    def delete(Note note)
    {

        if (note == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        note.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'note.label', default: 'Note'), note.id])

                redirect uri: request.getHeader("referer")
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'note.label', default: 'Note'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
